/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.SpdcfDAOInterface;
import com.wii.elpro.dao.hb.SpdcfDAOImpl;
import com.wii.elpro.dao.hb.PriceListMarketingDAOImpl;
import com.wii.elpro.dao.hb.ProdukDAOImpl;
import com.wii.elpro.dao.hb.CabangDAOImpl;
import com.wii.elpro.entity.Quotation;
import com.wii.elpro.entity.QuotationItem;
import com.wii.elpro.entity.Spdcf;
import com.wii.elpro.entity.SpdcfItem;
import com.wii.elpro.web.form.QuotationNewForm;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class QuotationNewAction extends DispatchAction {
        
    /**
     * This is the Struts action method called on
     * http://.../actionPath?method=myAction1,
     * where "method" is the value specified in <action> element : 
     * ( <action parameter="method" .../> )
     */
    public ActionForward generate(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        long id = Long.parseLong(request.getParameter("id"));
        SpdcfDAOInterface dao = new SpdcfDAOImpl();
        QuotationNewForm f = (QuotationNewForm) form;
        ActionMessages messages = new ActionMessages();
        HttpSession sess = request.getSession(true);
        List<QuotationItem> listItem = null;
        try {
            if(sess.getAttribute("listItem")!=null) {
                listItem = (List<QuotationItem>) sess.getAttribute("listItem");
            } else {
                listItem = null;
            }
            sess.setAttribute("listItem", listItem);
            
            Spdcf spdcf = dao.getSpdcf(id);
            f.setSpdcf(spdcf.getId());
            Quotation quotation = new Quotation();
            if(sess.getAttribute("quotation")!=null) {
                quotation = (Quotation) sess.getAttribute("quotation");
            } else {
                List<QuotationItem> items = new ArrayList<QuotationItem>();
                QuotationItem item = new QuotationItem();
                for(SpdcfItem i:spdcf.getItems()) {
                    item.setDisc(0);
                    item.setJumlah(i.getJumlah());
                    item.setPriceHppAndMarginKeuangan(i.getProduk().getHargaHpp().getHarga()*i.getProduk().getWeight()+(i.getMarginKeuangan()/100)*(i.getProduk().getHargaHpp().getHarga()*i.getProduk().getWeight()));
                    if(new PriceListMarketingDAOImpl().getPriceList(new ProdukDAOImpl().getProduk(i.getProduk().getId()), new CabangDAOImpl().getCabang(spdcf.getInquery().getSales().getCabang().getId()))!=null) {
                        item.setPriceList(new PriceListMarketingDAOImpl().getPriceList(new ProdukDAOImpl().getProduk(i.getProduk().getId()), new CabangDAOImpl().getCabang(spdcf.getInquery().getSales().getCabang().getId())).getPrice());
                    } else {
                        item.setPriceList(0);
                    }
                    item.setProduk(i.getProduk());
                    items.add(item);
//                    if(item.getDisc()!=0)
//                        total = total+item.getPriceList()*(item.getDisc()/100);
//                    else 
//                        total = total+item.getPriceList();
                }
                quotation.setItems(items);
                quotation.setSpdcf(spdcf);
                if(request.getAttribute("revisionNumber")!=null) {
                    quotation.setRevise(Integer.parseInt(request.getAttribute("revisionNumber")+"")+1);
                    System.out.println("---------------------BANG");
                }
                sess.setAttribute("quotation", quotation);
            }
            double total = 0;
            for(QuotationItem i:quotation.getItems()) {
                    total = (i.getPriceList()-(i.getPriceList()*i.getDisc())/100)+total;
            }
            request.setAttribute("total", total);
            request.setAttribute("date", new Date(System.currentTimeMillis()));
            request.setAttribute("spdcf", spdcf);
        } catch (Exception ex) {
            messages.add("message", new ActionMessage("customMessage", "Application is fail to save your data. Please contact my developer."));
            saveMessages(sess, messages);
            ex.printStackTrace();
        }
        return mapping.findForward("generate");
    }
    
    public ActionForward updateVat(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        double vat = 0;
        if(request.getParameter("val").isEmpty()) {
            vat=0;
        } else {
            vat=Double.parseDouble(request.getParameter("val"));
        }
        PrintWriter out = response.getWriter();
        out.print(vat);
        try {
         
        } catch (Exception ex) {
            ex.printStackTrace();
         
        }
        return null;
    }
    
    public ActionForward updateGrandTotal(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        HttpSession sess = request.getSession(true);
        double vat = 0;
        if(request.getParameter("val")!=null) {
            vat=Double.parseDouble(request.getParameter("val"));
        }
        double grandTotal = 0;
        if(sess.getAttribute("quotation")!=null) {
            Quotation quotation = (Quotation) sess.getAttribute("quotation");
            for(QuotationItem item: quotation.getItems()) {
                    grandTotal = (item.getPriceList()-item.getPriceList()*(item.getDisc()/100))+grandTotal;
            }
            grandTotal = grandTotal-(grandTotal*vat)/100;
//            System.out.println((grandTotal*vat)/100);
        }
        PrintWriter out = response.getWriter();
        NumberFormat nf = NumberFormat.getNumberInstance();
        out.print("Rp "+nf.format(grandTotal));
        
        return null;
    }

    /**
     * This is the Struts action method called on
     * http://.../actionPath?method=myAction2,
     * where "method" is the value specified in <action> element : 
     * ( <action parameter="method" .../> )
     */
    public ActionForward save(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String forward;
        QuotationNewForm f = (QuotationNewForm) form;
        SpdcfDAOInterface dao = new SpdcfDAOImpl();
        ActionMessages messages = new ActionMessages();
        HttpSession sess = request.getSession(true);
        Quotation quotation = (Quotation) sess.getAttribute("quotation");
        try {
            quotation.setDelivery(f.getDelivery());
            quotation.setLength(f.getLengt());
            quotation.setLoco(f.getLoco());
            quotation.setMatrial(f.getMatrial());
            quotation.setNoQuotation(new SpdcfDAOImpl().getSpdcf(f.getSpdcf()).getInquery().getNoQuotation());
            quotation.setPaymentTerm(f.getPaymentTerm());
            quotation.setPositionMatrial(f.getPositionMatrial());
            quotation.setPrice(f.getPrice());
            quotation.setSpdcf(new SpdcfDAOImpl().getSpdcf(f.getSpdcf()));
            quotation.setStatus(f.getStatus());
            quotation.setStatusDesc(f.getStatusDesc());
            quotation.setTglQuotation(new Date(System.currentTimeMillis()));
            quotation.setThickness(f.getThickness());
            DateFormat formatter;
            formatter = new SimpleDateFormat("yyyy-MM-d");
            if(f.getValidityPrice()!=null){
                quotation.setValidityPrice(formatter.parse(f.getValidityPrice()));
            }
            quotation.setValidityStock(f.getValidityStock());
            quotation.setVat(f.getVat());
//            quotation.setItems(quotation.getItems());  // Tidak perlu di set lagi karena object quotation ini sudah dapat items dari quotation yang disimpan di session
            dao.save(quotation);
            messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully saved."));
            forward = "save";
            sess.removeAttribute("quotation");
        } catch (Exception ex) {
            messages.add("message", new ActionMessage("customMessage", "Application is fail to save your data. Please contact my developer."));
            ex.printStackTrace();
            forward = "saveFail";
        }
        saveMessages(sess, messages);
        return mapping.findForward(forward);
    }
}
